﻿package {
	import org.cove.ape.*;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.ui.Keyboard;
	
	[SWF(width="800", height="600", backgroundColor="#FFFFFF")] 
	public class Joust extends Sprite {
		public static const STARTING_LIVES:uint = 3;
		public static const LIVES_HORIZONTAL_OFFSET:uint = 20;
		public static const LIVES_VERTICAL_OFFSET:uint = 20;
	
		public var player1:Controls;
		public var player2:Controls;

		private var paused:Boolean = false;
		
		[Embed(source="joust.swf", symbol="Logo")]
		public static var Logo:Class;
		public function Joust() {
			var logo:Sprite = new Logo();
			logo.x = 600;
			logo.y = 500;
			addChild(logo);
		
			// set up the events, main loop handler, and the engine. you don't have to use
			// enterframe. you just need to call the ApeEngine.step() and ApeEngine.paint() 
			// wherever and however you're handling your program cycle.
			stage.frameRate = 55;
			addEventListener(Event.ENTER_FRAME, run);
			
			APEngine.init(1/4);
			
			// set up the default diplay container
			APEngine.container = this;
			
			// gravity -- particles of varying masses are affected the same
			APEngine.addForce(new VectorForce(false, 0, .5));
			
			// groups - all these classes extend group
			var terrain:Terrain = new Terrain();
			APEngine.addGroup(terrain);
			
			var birdsGroup:Group = new Group(true);
			
			var bird1_mc:Bird = new Bird(200, 200);
			bird1_mc.addEventListener(JoustEvent.KILL, this.winHandler);
			birdsGroup.addParticle(bird1_mc);
			this.player1 = new Controls("w".charCodeAt(), "s".charCodeAt(), "a".charCodeAt(), "d".charCodeAt(), bird1_mc);
			bird1_mc.lives.x = LIVES_HORIZONTAL_OFFSET;
			bird1_mc.lives.y = LIVES_VERTICAL_OFFSET;
			addChild(bird1_mc.lives);
						
			var bird2_mc:Bird = new Bird(400, 200);
			bird2_mc.addEventListener(JoustEvent.KILL, this.winHandler);
			birdsGroup.addParticle(bird2_mc);
			this.player2 = new Controls(Keyboard.UP, Keyboard.DOWN, Keyboard.LEFT, Keyboard.RIGHT, bird2_mc);
			bird2_mc.lives.x = stage.stageWidth - bird2_mc.sprite.width - LIVES_HORIZONTAL_OFFSET;
			bird2_mc.lives.y = LIVES_VERTICAL_OFFSET;
			addChild(bird2_mc.lives);
			
			APEngine.addGroup(birdsGroup);
			
			// determine what collides with what.
			//birdsGroup.addCollidableList([terrain, this.player2.bird]);
			birdsGroup.addCollidable(terrain);
		}
		
		private function run(evt:Event):void {
			APEngine.step();
			APEngine.paint();
		}
		private function winHandler(evt:JoustEvent):void {
			// KEELL ZE LOZA
			evt.loser.lives.loseLife();
			if (evt.loser.lives.dead) {
				// handleWin
			} else {
				evt.loser.kill();
			}
		}
	}
}